package com.wbao.dianniu.viewpager;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PointF;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.ProgressBar;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.davemorrissey.labs.subscaleview.ImageSource;
import com.davemorrissey.labs.subscaleview.ImageViewState;
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView;
import com.wbao.dianniu.R;
import com.wbao.dianniu.logical.DnApplication;
import com.wbao.dianniu.utils.Downloader;

import java.lang.ref.WeakReference;


public class ImageFragment extends Fragment {


    private static final String IMAGE_URL = "image";
    private static final String IMAGE_SIZE = "image_size";
    private static final String IMAGE_INDEX = "image_index";
    //    PhotoView image;
    private String imageUrl;
    private Dialog dialog;
    private Activity mActivity;

    public ImageFragment() {
        // Required empty public constructor
    }

    public static ImageFragment newInstance(String param1/*,int size,int currentPage*/) {
        ImageFragment fragment = new ImageFragment();
        Bundle args = new Bundle();
        args.putString(IMAGE_URL, param1);
//        args.putInt(IMAGE_SIZE, size);
//        args.putInt(IMAGE_INDEX, currentPage);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            imageUrl = getArguments().getString(IMAGE_URL);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_image, container, false);
        final SubsamplingScaleImageView image = (SubsamplingScaleImageView) view.findViewById(R.id.scale_image_view);
        final ProgressBar mProgressBar = (ProgressBar) view.findViewById(R.id.loading_pic_progressbar);
        image.setMinimumScaleType(SubsamplingScaleImageView.SCALE_TYPE_CUSTOM);
//		image.setMinScale(0.8F);
        image.setMaxScale(5.0F);

        Glide.with(mActivity)    // .using(new ProgressModelLoader(new ProgressHandler(this, mProgressBar)))
                .load(imageUrl)
                .asBitmap()
                .placeholder(R.mipmap.ic_pig_rect)
                .diskCacheStrategy(DiskCacheStrategy.RESULT)
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {
                        if (isAdded()) {
                            mProgressBar.setVisibility(View.GONE);
                            float scale = (float) (image.getWidth() * 1.0f / (bitmap.getWidth() * 1.0f));
                            image.setImage(ImageSource.bitmap(bitmap), new ImageViewState(scale, new PointF(0, 0), 0));
                        }
                    }

                    @Override
                    public void onLoadFailed(Exception e, Drawable errorDrawable) {
                        super.onLoadFailed(e, errorDrawable);
                        if (isAdded()) {
                            mProgressBar.setVisibility(View.GONE);
                            Bitmap bitmap = BitmapFactory.decodeResource(mActivity.getResources(), R.mipmap.ic_pig_rect);
                            float scale = (float) (image.getWidth() * 1.0f / (bitmap.getWidth() * 1.0f));
                            image.setImage(ImageSource.resource(R.mipmap.ic_pig_rect), new ImageViewState(scale, new PointF(0, 0), 0));
                        }
                    }

                }).getRequest();

        image.setOnLongClickListener(new MyLongClickListener(imageUrl));
        image.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (null != mActivity) {
                    mActivity.finish();
                    mActivity.overridePendingTransition(0, R.anim.zoom_exit);
                }
            }
        });

        return view;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mActivity = (Activity) context;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mActivity = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    class MyLongClickListener implements OnLongClickListener {

        private String imagePath;

        public MyLongClickListener(String path) {
            // TODO Auto-generated constructor stub
            imagePath = path;
        }

        @Override
        public boolean onLongClick(View v) {
            showDialog(imagePath);
            return false;
        }
    }

    /**
     * 显示保存图片弹出框
     */
    private void showDialog(final String path) {
        dialog = new Dialog(getContext(), R.style.custom_Dialog);
        Window win = dialog.getWindow();
        win.getDecorView().setPadding(3, 3, 3, 3);
        win.setGravity(Gravity.BOTTOM);
        View view = LayoutInflater.from(getContext()).inflate(R.layout.qa_collection_dialog, null);
        Button collectBtn = (Button) view.findViewById(R.id.qa_collection_button);
        Button cancelBtn = (Button) view.findViewById(R.id.qa_collection_cancel);
        collectBtn.setText(getContext().getResources().getString(R.string.save_picture));
        //保存图片
        collectBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (null != dialog && dialog.isShowing()) {
                    dialog.dismiss();
                }
                // 保存图片到
                Downloader.download(mActivity, path);
            }
        });
        // 取消
        cancelBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (null != dialog && dialog.isShowing()) {
                    dialog.dismiss();
                }
            }
        });
        dialog.setContentView(view);
        dialog.setCancelable(true);
        dialog.show();
    }

    /**
     * file:// 7。0系统权限异常
     * public static void saveImageToGallery(Context context, Bitmap bmp) {
     * // 首先保存图片
     * File appDir = new File(Environment.getExternalStorageDirectory(), "Boohee");
     * if (!appDir.exists()) {
     * appDir.mkdir();
     * }
     * String fileName = System.currentTimeMillis() + ".jpg";
     * File file = new File(appDir, fileName);
     * try {
     * FileOutputStream fos = new FileOutputStream(file);
     * bmp.compress(CompressFormat.JPEG, 100, fos);
     * fos.flush();
     * fos.close();
     * } catch (FileNotFoundException e) {
     * e.printStackTrace();
     * } catch (IOException e) {
     * e.printStackTrace();
     * }
     * <p>
     * // 其次把文件插入到系统图库
     * try {
     * MediaStore.Images.Media.insertImage(context.getContentResolver(),
     * file.getAbsolutePath(), fileName, null);
     * } catch (FileNotFoundException e) {
     * e.printStackTrace();
     * }
     * // 最后通知图库更新
     * context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + Environment.getExternalStorageDirectory().getPath())));
     * }
     */


    private class ProgressHandler extends Handler {

        private final WeakReference<Fragment> mActivity;
        private final ProgressBar mProgressBar;

        public ProgressHandler(Fragment activity, ProgressBar progressBar) {
            super(Looper.getMainLooper());
            mActivity = new WeakReference<>(activity);
            mProgressBar = progressBar;
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            final Fragment activity = mActivity.get();
            if (activity != null) {
                switch (msg.what) {
                    case 1:
                        mProgressBar.setVisibility(View.VISIBLE);
//                        int percent = msg.arg1 * 100 / msg.arg2;
//                        mProgressBar.setProgress(percent);
//                        if (percent == 100) {
//                            mProgressBar.setVisibility(View.GONE);
//                        }
                        break;
                    default:
                        break;
                }
            }
        }
    }


}
